﻿#include "fastpointtaskform.h"
#include "ui_fastpointtaskform.h"
#include<QDir>
#include<QSettings>
#include<QString>
#include<QDebug>
#include "commontreedelegate.h"
FastPointTaskForm::FastPointTaskForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FastPointTaskForm)
{
    ui->setupUi(this);
    this->setObjectName("WidgetObjectFastPointTaskForm-InfraredBackground-BlackbodyScan-StarScan-sPaceScan");
    this->setWindowTitle(tr("FastPointTaskForm"));

    CommonTreeDelegate* delegate = new CommonTreeDelegate(this);
    QList<int> lstInt;
    lstInt.append(0);
    delegate->setColDisable(lstInt);

    ui->doubleSpinBox_Cycle->setValue(LoopTime);

    ui->PointWidget->setItemDelegate(delegate);
}

FastPointTaskForm::~FastPointTaskForm()
{
    delete ui;
}

void FastPointTaskForm::generateTask(TaskItem *pTask)
{
    TaskItem * pCurTask = NULL;
    if(!msCurTaskName.isEmpty())// 更新任务
    {
        pCurTask = TaskManager::getInstance()->getTask(msCurTaskName);
    }
    else
    {
        pCurTask = pTask;
    }

    CommandItem::FastTargetPos fastpos;
    for(int i=0; i<ui->PointWidget->rowCount(); ++i)
    {
        CommandItem* pCommandItem = pCurTask->getCommand(ui->PointWidget->item(i,Table_Name)->data(Qt::WhatsThisRole).toString());

        if(NULL == pCommandItem)
            pCommandItem = pCurTask->addCommand(ui->PointWidget->item(i,Table_Name)->text());

        fastpos.miTargetPosWorkMode=pCurTask->objectName();
        fastpos.mdTargetPosDuration=ui->PointWidget->item(i,Table_TotTime)->text().toDouble();

        // for first row
        pCommandItem->setWorkMode(CommandItem::Mode_FastPoint);
        pCommandItem->setFastPosMode(fastpos);
        pCommandItem->setValue(ScriptItem::Pos_EWStart,ui->PointWidget->item(i,Table_EWEnd)->text().toDouble());
        pCommandItem->setValue(ScriptItem::Pos_NSStart,ui->PointWidget->item(i,Table_NSEnd)->text().toDouble());
        pCommandItem->setValue(ScriptItem::Pos_EWEnd,ui->PointWidget->item(i,Table_EWEnd)->text().toDouble());
        pCommandItem->setValue(ScriptItem::Pos_NSEnd,ui->PointWidget->item(i,Table_NSEnd)->text().toDouble());
        pCommandItem->setValue(ScriptItem::Time_Start,ui->PointWidget->item(i,Table_STime)->text().toDouble());
        pCommandItem->setValue(ScriptItem::Time_End,ui->PointWidget->item(i,Table_ETime)->text().toDouble());

    }
}

void FastPointTaskForm::setCurrentTask(const QString &sName)
{
    // 如果窗口为关闭，再次切换回当前窗口，需要显示当前任务状态
    if(ui->PointWidget->rowCount() > 0)
    {
        return;
    }

    ui->lineEdit_CurTask->setText(sName);

    TaskEditor::setCurrentTask(sName);

    QDir settingDir(QDir::currentPath());
    settingDir.cdUp();
    settingDir.setPath(settingDir.absolutePath().append("/config/FY4TaskOptimization"));

    if(!settingDir.exists())
    {
        settingDir.mkdir(settingDir.absolutePath());
    }



    int nCmdCount = 1;
    double dEWPos = -5.2;
    double dNSPos = 5.35;
    double nStayTime =2;

    QSettings settings(settingDir.absoluteFilePath("setting.ini"),QSettings::IniFormat);

    if(sName.contains("InfraredBackground",Qt::CaseInsensitive))
    {
        settings.beginGroup(TaskManager::getInstance()->curIns().append("-InfraredBackground"));
        if(settings.contains("InfraredBackgroundCmdCount"))
            nCmdCount = settings.value("InfraredBackgroundCmdCount").toInt();
        else{
            if(TaskManager::getInstance()->curIns().contains("FY4B-Agr"))

            {
                nCmdCount=5;
            }
            else
                nCmdCount = 3;
            settings.setValue("InfraredBackgroundCmdCount",nCmdCount);

        }
        if(settings.contains("InfraredBackgroundStayTime"))
        {
            nStayTime=settings.value("InfraredBackgroundStayTime").toDouble();
        }
        else
        {
            settings.setValue("InfraredBackgroundStayTime",QString::number(nStayTime,'f',6));
        }
        ui->PointWidget->setRowCount(nCmdCount);
        for(int i=0; i<nCmdCount; ++i)
        {
            if(!settings.contains(QString("InfraredBackground%1").arg(i+1)))
            {
                settings.setValue(QString("InfraredBackground%1").arg(i+1),QString("%1,%2").arg(dEWPos).arg(dNSPos));
                ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(QString::number(dEWPos,'f',6)));
                ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(QString::number(dNSPos,'f',6)));
            }
            else
            {
                QString sContext = settings.value(QString("InfraredBackground%1").arg(i+1)).toString();
                ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(sContext.section(",",0,0)));
                ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(sContext.section(",",1,1)));
            }
	
          //  ui->PointWidget->setItem(i,Table_Name,new QTableWidgetItem(QString("InfraredBackground %1").arg(i+1)));
            ui->PointWidget->setItem(i,Table_Name,new QTableWidgetItem(QString("InfraredBackground %1-%2").arg(i+1).arg(nCmdCount)));
		    ui->PointWidget->setItem(i,Table_TotTime,new QTableWidgetItem(QString::number(nStayTime,'f',6)));
            QTableWidgetItem* pModeItem = new QTableWidgetItem();
            pModeItem->setData(Qt::DisplayRole,true);
            ui->PointWidget->setItem(i,Table_WorkMode,pModeItem);

            if(i == 0)
            {
                ui->PointWidget->setItem(i,Table_STime,new QTableWidgetItem(QString::number(0.0,'f',6)));
            }
        }
        settings.endGroup();
    }
    else if(sName.contains("BlackbodyScan",Qt::CaseInsensitive))
    {
        settings.beginGroup(TaskManager::getInstance()->curIns().append("-BlackbodyScan"));
        if(settings.contains("BlackbodyScanCmdCount"))
            nCmdCount = settings.value("BlackbodyScanCmdCount").toInt();
        else{
            nCmdCount = 1;
            settings.setValue("BlackbodyScanCmdCount",nCmdCount);

        }
        if(settings.contains("BlackbodyScanStayTime"))
        {
            nStayTime=settings.value("BlackbodyScanStayTime").toDouble();
        }
        else
        {
            settings.setValue("BlackbodyScanStayTime",QString::number(nStayTime,'f',6));
        }
        ui->PointWidget->setRowCount(nCmdCount);
        for(int i=0; i<nCmdCount; ++i)
        {
            if(!settings.contains(QString("BlackbodyScan%1").arg(i+1)))
            {
                dEWPos=0;
                dNSPos=90;
                settings.setValue(QString("BlackbodyScan%1").arg(i+1),QString("%1,%2").arg(dEWPos).arg(dNSPos));
                ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(QString::number(dEWPos,'f',6)));
                ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(QString::number(dNSPos,'f',6)));
            }
            else
            {
                QString sContext = settings.value(QString("BlackbodyScan%1").arg(i+1)).toString();
                ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(sContext.section(",",0,0)));
                ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(sContext.section(",",1,1)));
            }
            ui->PointWidget->setItem(i,Table_Name,new QTableWidgetItem(QString("BlackbodyScan %1").arg(i+1)));
            ui->PointWidget->setItem(i,Table_TotTime,new QTableWidgetItem(QString::number(nStayTime,'f',6)));
            QTableWidgetItem* pModeItem = new QTableWidgetItem();
            pModeItem->setData(Qt::DisplayRole,true);
            ui->PointWidget->setItem(i,Table_WorkMode,pModeItem);

            if(i == 0)
            {
                ui->PointWidget->setItem(i,Table_STime,new QTableWidgetItem(QString::number(0.0,'f',6)));
            }
        }
        settings.endGroup();
    }
    else if(sName.contains("StarScan",Qt::CaseInsensitive))
    {
        settings.beginGroup(TaskManager::getInstance()->curIns().append("-StarScan"));
        if(settings.contains("StarScanCmdCount"))
            nCmdCount = settings.value("StarScanCmdCount").toInt();
        else{
            nCmdCount = 5;
            settings.setValue("StarScanCmdCount",nCmdCount);

        }
        if(settings.contains("StarScanStayTime"))
        {
            nStayTime=settings.value("StarScanStayTime").toDouble();
        }
        else
        {
            nStayTime=5;
            settings.setValue("StarScanStayTime",nStayTime);
        }
        ui->PointWidget->setRowCount(nCmdCount);
        for(int i=0; i<nCmdCount; ++i)
        {
            if(!settings.contains(QString("StarScan%1").arg(i+1)))
            {
                dEWPos=0;
                dNSPos=0;
                settings.setValue(QString("StarScan%1").arg(i+1),QString("%1,%2").arg(dEWPos).arg(dNSPos));
                ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(QString::number(dEWPos,'f',6)));
                ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(QString::number(dNSPos,'f',6)));
            }
            else
            {
                QString sContext = settings.value(QString("StarScan%1").arg(i+1)).toString();
                ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(sContext.section(",",0,0)));
                ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(sContext.section(",",1,1)));
            }

            ui->PointWidget->setItem(i,Table_Name,new QTableWidgetItem(QString("StarScan %1").arg(i+1)));
            ui->PointWidget->setItem(i,Table_TotTime,new QTableWidgetItem(QString::number(nStayTime,'f',6)));
            QTableWidgetItem* pModeItem = new QTableWidgetItem();
            pModeItem->setData(Qt::DisplayRole,true);
            ui->PointWidget->setItem(i,Table_WorkMode,pModeItem);


            ui->PointWidget->setItem(i,Table_STime,new QTableWidgetItem(QString::number(0.0,'f',6)));
        }
        settings.endGroup();
    }
    else if(sName.contains("sPaceScan",Qt::CaseInsensitive))
    {
        settings.beginGroup(TaskManager::getInstance()->curIns().append("-sPaceScan"));
        if(settings.contains("sPaceScanCmdCount"))
        {
            nCmdCount = settings.value("sPaceScanCmdCount").toInt();
        }
        else
        {
            nCmdCount=1;
            settings.setValue("sPaceScanCmdCount",nCmdCount);
        }
        if(settings.contains("sPaceScanStayTime"))
        {
            nStayTime=settings.value("sPaceScanStayTime").toDouble();
        }
        else
        {
            nStayTime=2;
            settings.setValue("sPaceScanStayTime",QString::number(nStayTime,'f',6));
        }
        ui->PointWidget->setRowCount(nCmdCount);
        for(int i=0; i<nCmdCount; ++i)
        {
            if(!settings.contains(QString("sPaceScan%1").arg(i+1)))
            {
                dEWPos=-5.2;
                dNSPos=5.35;
                settings.setValue(QString("sPaceScan%1").arg(i+1),QString("%1,%2").arg(dEWPos).arg(dNSPos));
                ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(QString::number(dEWPos,'f',6)));
                ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(QString::number(dNSPos,'f',6)));
            }
            else
            {
                QString sContext = settings.value(QString("sPaceScan%1").arg(i+1)).toString();
                ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(sContext.section(",",0,0)));
                ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(sContext.section(",",1,1)));
            }

            ui->PointWidget->setItem(i,Table_Name,new QTableWidgetItem(QString("sPaceScan %1").arg(i+1)));
            ui->PointWidget->setItem(i,Table_TotTime,new QTableWidgetItem(QString::number(nStayTime,'f',6)));
            QTableWidgetItem* pModeItem = new QTableWidgetItem();
            pModeItem->setData(Qt::DisplayRole,true);
            ui->PointWidget->setItem(i,Table_WorkMode,pModeItem);
            ui->PointWidget->setItem(i,Table_STime,new QTableWidgetItem(QString::number(0.0,'f',6)));
        }
        settings.endGroup();
    }
    else
    {
        TaskEditor::setCurrentTask(sName);
    }
    TaskEditor::setCurrentTask(sName);
}


void FastPointTaskForm::on_pushButton_AddCycle_clicked()
{
    if(ui->lineEdit_CurTask->text().contains("StarScan"))
    {
        int rownumber=ui->PointWidget->currentRow();
        double sTime =ui->PointWidget->item(rownumber,Table_STime)->text().toDouble() + ui->doubleSpinBox_Cycle->value();
        if(sTime<0)
            return;
        ui->PointWidget->item(rownumber,Table_STime)->setText(QString::number(sTime,'f',6));
        double dTime =ui->PointWidget->item(rownumber,Table_ETime)->text().toDouble() + ui->doubleSpinBox_Cycle->value();
        ui->PointWidget->item(rownumber,Table_ETime)->setText(QString::number(dTime,'f',6));
        return ;
    }
    for(int i=ui->PointWidget->currentRow(); i<ui->PointWidget->rowCount(); ++i)
    {
        double sTime =ui->PointWidget->item(i,Table_STime)->text().toDouble() + ui->doubleSpinBox_Cycle->value();
        ui->PointWidget->item(i,Table_STime)->setText(QString::number(sTime,'f',6));
        double dTime =ui->PointWidget->item(i,Table_ETime)->text().toDouble() + ui->doubleSpinBox_Cycle->value();
        ui->PointWidget->item(i,Table_ETime)->setText(QString::number(dTime,'f',6));
    }
}
void FastPointTaskForm::on_pushButton_DeCycle_clicked()
{
    if(ui->lineEdit_CurTask->text().contains("StarScan"))
    {
        int rownumber=ui->PointWidget->currentRow();
        double sTime =ui->PointWidget->item(rownumber,Table_STime)->text().toDouble() - ui->doubleSpinBox_Cycle->value();
        if(sTime<0)
            return;
        ui->PointWidget->item(rownumber,Table_STime)->setText(QString::number(sTime,'f',6));
        double dTime =ui->PointWidget->item(rownumber,Table_ETime)->text().toDouble() - ui->doubleSpinBox_Cycle->value();
        ui->PointWidget->item(rownumber,Table_ETime)->setText(QString::number(dTime,'f',6));
        return;
    }
    for(int i=ui->PointWidget->currentRow(); i<ui->PointWidget->rowCount(); ++i)
    {
        double sTime =ui->PointWidget->item(i,Table_STime)->text().toDouble() - ui->doubleSpinBox_Cycle->value();
        if(sTime<=0)
            break;
        ui->PointWidget->item(i,Table_STime)->setText(QString::number(sTime,'f',6));
        double dTime =ui->PointWidget->item(i,Table_ETime)->text().toDouble() - ui->doubleSpinBox_Cycle->value();
        ui->PointWidget->item(i,Table_ETime)->setText(QString::number(dTime,'f',6));
    }
}
void FastPointTaskForm::setCurrentMode(int nMode)
{
    // 不属于添加模式，部分按钮应该隐藏
    if(nMode != 0)
    {
        ui->pushButton_AddTimes->setEnabled(false);
        ui->pushButton_DeduceTimes->setEnabled(false);
    }

    TaskEditor::setCurrentMode(nMode);
}

void FastPointTaskForm::updateTask(TaskItem *pTask)
{
    if(NULL == pTask)
        return;
    msCurTaskName = pTask->objectName();

    QVector<CommandItem *> vctCmds = pTask->allCommands();
    ui->PointWidget->setRowCount(vctCmds.count());
    for(int i=0; i<vctCmds.count(); ++i){
        QTableWidgetItem* pTableItem = new QTableWidgetItem(vctCmds.at(i)->getName());
        // 设置对象名称，为了在计算的时候不重新添加，同时可在更新的时候方便查找
        pTableItem->setData(Qt::WhatsThisRole,vctCmds.at(i)->objectName());

        ui->PointWidget->setItem(i,Table_Name,pTableItem);
        ui->PointWidget->setItem(i,Table_EWStart,new QTableWidgetItem(QString::number(vctCmds.at(i)->getValue(ScriptItem::Pos_EWStart),'f',6)));
        ui->PointWidget->setItem(i,Table_EWEnd,new QTableWidgetItem(QString::number(vctCmds.at(i)->getValue(ScriptItem::Pos_EWEnd),'f',6)));
        ui->PointWidget->setItem(i,Table_NSStart,new QTableWidgetItem(QString::number(vctCmds.at(i)->getValue(ScriptItem::Pos_NSEnd),'f',6)));
        ui->PointWidget->setItem(i,Table_NSEnd,new QTableWidgetItem(QString::number(vctCmds.at(i)->getValue(ScriptItem::Pos_NSEnd),'f',6)));

        double dTimeStart = vctCmds.at(i)->getValue(ScriptItem::Time_Start);
        double dTimeEnd = vctCmds.at(i)->getValue(ScriptItem::Time_End);

        ui->PointWidget->setItem(i,Table_STime,new QTableWidgetItem(QString::number(dTimeStart,'f',6)));
        ui->PointWidget->setItem(i,Table_ETime,new QTableWidgetItem(QString::number(dTimeEnd,'f',6)));
        ui->PointWidget->setItem(i,Table_TotTime,new QTableWidgetItem(QString::number(dTimeEnd-dTimeStart,'f',6)));
        if(i==0)
        {
            ui->PointWidget->setCurrentItem(pTableItem);
        }
    }
}


void FastPointTaskForm::on_pushButton_CalPos_clicked()
{
    //读取到配置文件中的指令间隔时间,调用这个计算快速指向的函数上一个点位置的坐标和这个点的位置坐标。
    double starttime=0.0;
    double endtime=0.0;
    double startposx=0.0;
    double startposy=0.0;
    for(int i=0;i<ui->PointWidget->rowCount();++i)
    {
        //设置开始时间和结束时间。
        //如果是红外背景，第一行开始时间为0，第二行开始时间为上一行的结束时间加上快速指向的时间。
        if(ui->lineEdit_CurTask->text()=="InfraredBackground")
        {
            if(i)
            {
                double ddx = abs(startposx-ui->PointWidget->item(i,Table_EWEnd)->text().toDouble());
                double ddy = abs(startposy-ui->PointWidget->item(i,Table_NSEnd)->text().toDouble());
                double realDis = qMax(ddx,ddy);

                starttime=endtime+TaskManager::getInstance()->currentInstrument()->getScanTime(0,realDis,TaskManager::getInstance()->currentInstrument()->mdScanFastPointSpeed);
//                starttime=endtime+TaskManager::getInstance()->currentInstrument()->getQuickTime(startposx,startposy,
//                                                                                                ui->PointWidget->item(i,Table_EWEnd)->text().toDouble(),
//                                                                                                ui->PointWidget->item(i,Table_NSEnd)->text().toDouble(),
//                                                                                                TaskManager::getInstance()->currentInstrument()->mdScanFastPointSpeed);
                qDebug()<<"point index"<<i<<TaskManager::getInstance()->currentInstrument()->instrumentName()<<TaskManager::getInstance()->currentInstrument()->mdScanFastPointSpeed<<starttime;

            }
            else
                starttime=ui->PointWidget->item(i,Table_STime)->text().toDouble()+TaskManager::getInstance()->currentInstrument()->getQuickTime(startposx,startposy,
                                                                                                                                                ui->PointWidget->item(i,Table_EWEnd)->text().toDouble(),
                                                                                                                                                ui->PointWidget->item(i,Table_NSEnd)->text().toDouble(),
                                                                                                                                                TaskManager::getInstance()->currentInstrument()->mdFastPointSpeed);
            startposx=ui->PointWidget->item(i,Table_EWEnd)->text().toDouble();
            startposy=ui->PointWidget->item(i,Table_NSEnd)->text().toDouble();
        }
        else
            starttime=ui->PointWidget->item(i,Table_STime)->text().toDouble();

        endtime=starttime+ui->PointWidget->item(i,Table_TotTime)->text().toDouble();

        //如果有值就改值，没值就new防止内存泄漏。
        if(ui->PointWidget->item(i,Table_STime)==0)
            ui->PointWidget->setItem(i,Table_STime,new QTableWidgetItem(QString::number(starttime,'f',6)));
        else
        {
            ui->PointWidget->item(i,Table_STime)->setText(QString::number(starttime,'f',6));
        }
        ui->PointWidget->setItem(i,Table_ETime,new QTableWidgetItem(QString::number(endtime,'f',6)));

        endtime+=instructionIntervalTime;
    }
    ui->PointWidget->setCurrentCell(0,Table_STime);
}
void FastPointTaskForm::on_pushButton_AddTimes_clicked()
{
    //取出上一行的数据，加入到这一行。
    int nRow = ui->PointWidget->currentRow();
    if(nRow < 0)
        nRow = 0;
    ui->PointWidget->insertRow(nRow+1);
	//20210226
    //ui->PointWidget->setItem(nRow+1,Table_Name,new QTableWidgetItem(tr("%1 %2").arg(ui->PointWidget->item(nRow,0)->text().section(" ",0,0)).arg(ui->PointWidget->rowCount())));
     ui->PointWidget->setItem(nRow+1,Table_Name,new QTableWidgetItem(tr("%1 %2-%3").arg(ui->PointWidget->item(nRow,0)->text().section(" ",0,0)).arg(ui->PointWidget->rowCount()).arg(ui->PointWidget->rowCount())));
	ui->PointWidget->setItem(nRow+1,Table_WorkMode,new QTableWidgetItem(ui->PointWidget->item(nRow,1)->text()));
    ui->PointWidget->setItem(nRow+1,Table_EWEnd,new QTableWidgetItem(ui->PointWidget->item(nRow,2)->text()));
    ui->PointWidget->setItem(nRow+1,Table_NSEnd,new QTableWidgetItem(ui->PointWidget->item(nRow,3)->text()));
    ui->PointWidget->setItem(nRow+1,Table_STime,new QTableWidgetItem());
    ui->PointWidget->setItem(nRow+1,Table_ETime,new QTableWidgetItem());
    ui->PointWidget->setItem(nRow+1,Table_TotTime,new QTableWidgetItem(ui->PointWidget->item(nRow,6)->text()));
}

void FastPointTaskForm::on_pushButton_DeduceTimes_clicked()
{
    int nCurRow = ui->PointWidget->currentRow();
    if(nCurRow < 0)
        nCurRow = 0;

    ui->PointWidget->removeRow(nCurRow);
}

void FastPointTaskForm::on_pushButton_saveToConfig_clicked()
{
    //配置文件中的x和y位置数据
    QString str1;
    QString str2;

    QDir settingDir(QDir::currentPath());
    settingDir.cdUp();
    settingDir.setPath(settingDir.absolutePath().append("/config/FY4TaskOptimization"));
    QSettings settings(settingDir.absoluteFilePath("setting.ini"),QSettings::IniFormat);
    settings.beginGroup(TaskManager::getInstance()->curIns());

    //配置文件无论有没有，运行到此处，就已经有内容了。只要根据name修改setting的值就可以了。
    for(int i=0;i<ui->PointWidget->rowCount();++i)
    {
        str1=ui->PointWidget->item(i,Table_EWEnd)->text();
        str2=ui->PointWidget->item(i,Table_NSEnd)->text();
        settings.setValue(ui->PointWidget->item(i,0)->text(),str1+","+str2);
    }
    settings.setValue(QString("%1StayTime").arg(ui->lineEdit_CurTask->text()),ui->PointWidget->item(0,Table_TotTime)->text().toDouble());
    settings.endGroup();
}
